<template>
  <div class="addressPage">
    <van-nav-bar
      title="编辑地址"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    >
    </van-nav-bar>
    <van-address-edit
      :address-info="addressInfo"
      :area-list="areaList"
      show-postal
      show-delete
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @change-default="onChangeDfault"
      @save="onSave"
      @delete="onDelete"
      @change-detail="onChangeDetail"
    />
  </div>
</template>
<script>
import { areaList } from "@vant/area-data";
export default {
  name: "AddressEdit",
  data() {
    return {
      Addressid: 1,
      addressInfo: {},
      areaList,
      searchResult: [],
      editIndex: -1,
    };
  },
  methods: {
    async onSave(content) {
      let data = null;
      if (!this.editIndex) {
        let Addressid = -1;
        data = await this.$store.dispatch("address/addAddress", {
          ...content,
          Addressid: Addressid,
        });
      } else {
        let Addressid =
          this.$store.state.address.address[this.editIndex].Addressid;
        data = await this.$store.dispatch("address/addAddress", {
          ...content,
          Addressid: Addressid,
        });
      }
      //添加地址
      if (data.status === 500) {
        this.$notify({ type: "danger", message: "添加地址错误" });
      } else if (data.status === 200) {
        //添加成功
        this.$notify({ type: "success", message: "添加地址成功" });
      }
    },
    //切换默认
    onChangeDfault(value) {},
    //删除地址
    async onDelete(content) {
      const data = await this.$store.dispatch(
        "address/delAddress",
        this.addressid
      );
      //删除地址失败
      if (data.status === 500) {
        this.$notify({ type: "danger", message: "删除地址错误" });
      } else if (data.status === 200) {
        //删除地址成功
        this.$notify({ type: "success", message: "删除地址成功" });
        this.$router.replace("address");
      }
    },
    onChangeDetail(val) {
      if (val) {
        this.searchResult = [
          {
            name: "永泰学山文化创意谷",
            address: "广州市白云区",
          },
        ];
      } else {
        this.searchResult = [
          {
            name: "暂不支持相关定位推荐",
            address: "烦请手动输入详情地址",
          },
        ];
      }
    },
    // 2021/11/3
  },
  created() {
    /* 拿路由参数设置默认值 */
    if (!this.$route.params) {
      return;
    }
    const {
      Name,
      Phonenum,
      isDefault,
      Address,
      AddressDetail,
      PostalCode,
      Addressid,
      index,
    } = this.$route.params;
    this.addressid = Addressid;
    this.editIndex = index;
    this.addressInfo = {
      name: Name,
      tel: Phonenum,
      isDefault,
      addressDetail: AddressDetail,
      postalCode: PostalCode,
    };
  },
};
</script>